import Icon from '@/components/Icon'
import NavBar from '@/components/NavBar'
import classnames from 'classnames'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router'
import styles from './index.module.scss'
import { getSuggestList, clearSuggestions, saveHistioiesList, clearHistories } from '@/store/actions/search'
import { RootType } from '@/store'

const Search = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const [keyWord, setKeyWord] = useState('')
  const timerRef = useRef(-1)
  // 控制搜索历史和联想建议切换显示
  const [isSearching, setIsSearching] = useState(false)
  // 搜索建议列表
  const suggestions = useSelector((state: RootType) => state.search.suggestion)
  const histories = useSelector((state: RootType) => state.search.histories)

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const text = e.target.value
    setKeyWord(text)
    // 发请求要处理防抖
    window.clearTimeout(timerRef.current) // 每次都要清空上次的定时器
    timerRef.current = window.setTimeout(() => {
      if (text) {
        setIsSearching(true)
        dispatch(getSuggestList(text) as any)
      } else {
        setIsSearching(false)
      }
    }, 500)
  }

  // 组件销毁的时候要清除定时器
  useEffect(() => {
    return () => window.clearTimeout(timerRef.current)
  }, [])

  // 让指定字符串高亮
  const highLight = (str: string, key: string) => {
    return str.replace(new RegExp(key, 'gi'), (match: string) => {
      return `<span style="color: red">${match}</span>`
    })
  }

  // 清空输入框里面的数据
  const onClear = () => {
    // 清空输入框中的数据
    setKeyWord('')
    // 控制历史记录和联想建议的显示状态
    setIsSearching(false)
    // 清空redux中的数据
    dispatch(clearSuggestions() as any)
  }

  // 点击搜索按钮触发
  const onSearch = (key: string) => {
    // console.log(key)
    if (!key) return
    // 保存到本地和redux中
    dispatch(saveHistioiesList(key) as any)
    // 跳转到搜索结果的文章列表
    history.push(`/search/result?key=${key}`)
  }

  // 清空历史记录
  const onClearHistory = () => {
    dispatch(clearHistories() as any)
  }

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar
        className="navbar"
        leftClick={() => history.go(-1)}
        extra={
          <span className="search-text" onClick={() => onSearch(keyWord)}>
            搜索
          </span>
        }
      >
        <div className="navbar-search">
          <Icon type="iconbtn_search" className="icon-search" />

          <div className="input-wrapper">
            {/* 输入框 */}
            <input type="text" placeholder="请输入关键字搜索" value={keyWord} onChange={onChange} />

            {/* 清空输入框按钮 */}
            <Icon type="iconbtn_tag_close" className="icon-close" onClick={onClear} />
          </div>
        </div>
      </NavBar>

      {/* 搜索历史 */}
      <div className="history" style={{ display: isSearching ? 'none' : 'block' }}>
        <div className="history-header">
          <span>搜索历史</span>
          <span onClick={onClearHistory}>
            <Icon type="iconbtn_del" />
            清除全部
          </span>
        </div>

        <div className="history-list">
          {histories.map((item, index) => (
            <span className="history-item" key={index} onClick={() => onSearch(item)}>
              {index !== 0 && <span className="divider"></span>}
              {item}
            </span>
          ))}
        </div>
      </div>

      {/* 搜素建议结果列表 */}
      <div className={classnames('search-result', isSearching ? 'show' : false)}>
        {suggestions.map((item, index) => (
          <div className="result-item" key={index} onClick={() => onSearch(item)}>
            <Icon className="icon-search" type="iconbtn_search" />
            <div className="result-value" dangerouslySetInnerHTML={{ __html: highLight(item, keyWord) }}></div>
          </div>
        ))}
      </div>
    </div>
  )
}

export default Search
